package controllers

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"pipline_build_tag/conf"
	"pipline_build_tag/model"
	"pipline_build_tag/utils"
	"sort"
	"strings"
	"time"
)

var logw = utils.WriteLog()

type Request struct {
	Name          string `json:"name"`
	Node          string `json:"node"`
	Tag           string `json:"tag"`
	Token         string `json:"tocken"`
	CommitMessage string `json:"commitmessage"`
}

// 添加标签
func AddTag(context *gin.Context) {
	var req Request
	err := context.ShouldBindJSON(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("添加标签不完整的请求参数", err.Error())
		return
	}

	if len(req.Name) == 0 || len(req.Node) == 0 || len(req.Tag) == 0 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("添加标签不完整的请求参数值", err.Error())
		return
	}

	if req.Token != conf.Server.Auth.TOKEN {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的鉴权",
		})
		logw.Println("添加标签鉴权失败 TOKEN 不匹配")
		return
	}

	//获取当前时间
	now := time.Now()
	//格式化时间
	formatted := now.Format("2006-01-02 15:04:05")

	var dockertag = &model.DockerTag{
		Name:          req.Name,
		NodeName:      req.Node,
		Tag:           req.Tag,
		DateTag:       formatted,
		CommitMessage: req.CommitMessage,
	}
	//存入数据
	row := model.DB.Create(&dockertag).RowsAffected
	if row != 0 {
		context.JSON(http.StatusOK, gin.H{
			"code":    "200",
			"message": req.Tag,
			"name":    req.Name,
			"node":    req.Node,
		})
		return
	}
}

// 获取标签时间
func GetTagDate(context *gin.Context) {
	var req Request
	err := context.ShouldBindJSON(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("获取标签时间不完整的请求参数", err.Error())
		return
	}
	if len(req.Name) == 0 || len(req.Node) == 0 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("获取标签时间不完整的请求参数值", err.Error())
		return
	}

	if req.Token != conf.Server.Auth.TOKEN {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的鉴权",
		})
		logw.Println("获取标签时间鉴权失败 TOKEN 不匹配")
		return
	}
	var date_tag []model.DockerTag
	model.DB.Select("date_tag, commit_message").Where("name = ? and node_name = ?", req.Name, req.Node).Find(&date_tag)
	var data = map[string][]string{}
	//遍历生成数据
	for _, tag := range date_tag {
		data["date"] = append(data["date"], tag.DateTag+"["+tag.CommitMessage+"]")
	}

	//降序排序
	sort.Slice(data["date"], func(i, j int) bool {
		return data["date"][i] > data["date"][j]
	})
	//将排序后的字符串切片转换回map[string][]string{}类型
	for i, s := range data["date"] {
		data["date"][i] = s
	}

	//返回参数
	context.JSON(http.StatusOK, data)
}

// 根据时间查询对应的tag
func GetTag(context *gin.Context) {
	var req Request
	err := context.ShouldBindJSON(&req)
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("获取tag不完整的请求参数", err.Error())
		return
	}
	if len(req.Name) == 0 || len(req.Node) == 0 || len(req.Tag) == 0 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的请求参数",
		})
		logw.Println("获取tag不完整的请求参数值", err.Error())
		return
	}

	if req.Token != conf.Server.Auth.TOKEN {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    "400",
			"message": "错误的鉴权",
		})
		logw.Println("获取tag鉴权失败 TOKEN 不匹配")
		return
	}

	index := strings.Index(req.Tag, "[")

	var date_tag string
	err = model.DB.Table("docker_tags").Select("tag").Where("name = ? and node_name = ? and date_tag = ?", req.Name, req.Node, string(req.Tag[:index])).Find(&date_tag).Limit(1).Error
	if err != nil {
		log.Println(err.Error())
		return
	}
	//返回TAG
	context.String(http.StatusOK, date_tag)
}
